<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <title>食物消消乐</title>
    <meta name="viewport" content="width=device-width, initial-scale=1.0, user-scalable=no,initial-scale=1, maximum-scale=1">
    <meta name="apple-mobile-web-app-capable" content="yes">
    <meta name="apple-mobile-web-app-status-bar-style" content="black">
    <style>
    /*全局公用样式*/
    body{margin:0;padding:0;color:#000;font-size:12px; font-family:"微软雅黑"; background:#FFF; line-height:21px;}
    form,input,div,dl,dt,dd,ul,ol,li,table,tr,th,td,textarea,form,botton,img,h1,h2,h3,h4,h5,h6,p{border:0;margin:0;padding:0;}
    img{border:0;vertical-align:top;width: auto; height: auto; max-width: 100%;}
    input[type="text"]{-webkit-appearance: none;}
    /*列表公用样式*/
    ul,li{list-style:none;}
    /*浮动公用样式*/
    .left{float:left}
    .right{float:right}
    .clear{clear:both}
    strike{ color:#8c8c8c;}
    i,h1,h2{ font-style:normal;}
    .titleBox{
        width:100%;
        height:40px;
        line-height:40px;
        font-size:16px;
        text-align:center;
        color:#e6703c;
        font-weight:700;
        background-color:#faf4ea;
    }
    .titleBox .scoreBox{
        font-weight:500;
        font-size:16px;
        height:40px;
        line-height:40px;
    }
    .tipBox{
        display:none;
        position:absolute;
        top:80px;
        left:50%;
        width:320px;
        height:340px;
        margin-left:-160px;
        text-align:center;
        color:#e6703c;
        background-color:rgba(144,121,82,0.6);
        border-radius:10px;
        -webkit-box-shadow:0 0 10px rgba(125,89,30,0.6);  
        -moz-box-shadow:0 0 10px rgba(125,89,30,0.6);  
        box-shadow:0 0 10px rgba(125,89,30,0.6); 
        z-index:999;
    }
    .tipBox img{
        width:200px;
        height:186.5px;
        margin-top:72px;
    }
    .createBox{
        position:fixed;
        bottom:0;
        width:100%;
        text-align:center;
        color:#aaa;

    }
    .tableBox{
        position:relative;
        width:300px;
        height:300px;
        border:1px solid #eee;
        margin:60px auto;
    }
    .row{
        width:100%;
        height:60px;
        overflow:hidden;
    }
    .cell{
        float:left;
        width:58px;
        height:58px;
        line-height:58px;
        border:1px solid #fff;
        text-align:center;
        border-radius:10px;
        background-size:100% 100%;
        background-color:#faf4ea;
    }
    .cell.active{
        border:1px solid #e19b20;
    }
    .cell.type0{
        background-image:url(img/food0.png);
    }
    .cell.type1{
        background-image:url(img/food1.png);
    }
    .cell.type2{
        background-image:url(img/food2.png);
    }
    .cell.type3{
        background-image:url(img/food3.png);
    }
    .cell.type4{
        background-image:url(img/food4.png);
    }
    .cell.animateEle{
        position:absolute;
    }

/*    .cell.type0{
        background-color:#e8c646;
    }
    .cell.type1{
        background-color:#52bf52;
    }
    .cell.type2{
        background-color:#6e6ce8;
    }
    .cell.type3{
        background-color:#e47be4;
    }
    .cell.type4{
        background-color:#42d6d6;
    }*/
    </style>
    </head>
    <body>
    <div class="titleBox">
        分数：<span class="scoreBox" id="scoreBox"></span>
    </div>
    <div class="tipBox" id="tipBox">
        <img src="img/eat.png" alt="">
    </div>
<!--       <div class="tableBox" id="tableBox">

          <div class="cell dragEle type0"><i></i></div>
          <div class="cell dragEle type1"><i></i></div>
          <div class="cell dragEle type4"><i></i></div>
          <div class="cell dragEle type3"><i></i></div>
          <div class="cell dragEle type1"><i></i></div>
          <div class="cell dragEle type1"><i></i></div>
          <div class="cell dragEle type1"><i></i></div>
          <div class="cell dragEle type3"><i></i></div>
          <div class="cell dragEle type4"><i></i></div>
          <div class="cell dragEle type2"><i></i></div>
          <div class="cell dragEle type2"><i></i></div>
          <div class="cell dragEle type2"><i></i></div>
          <div class="cell dragEle type4"><i></i></div>
          <div class="cell dragEle type2"><i></i></div>
          <div class="cell dragEle type2"><i></i></div>
          <div class="cell dragEle type0"><i></i></div>
          <div class="cell dragEle type1"><i></i></div>
          <div class="cell dragEle type4"><i></i></div>
          <div class="cell dragEle type3"><i></i></div>
          <div class="cell dragEle type1"><i></i></div>
          <div class="cell dragEle type1"><i></i></div>
          <div class="cell dragEle type4"><i></i></div>
          <div class="cell dragEle type2"><i></i></div>
          <div class="cell dragEle type2"><i></i></div>
          <div class="cell dragEle type1"><i></i></div>
      </div> -->
    <div class="tableBox" id="tableBox"></div>
<!--       <div class="tableBox" id="tableBox">
        <div class="row">
          <div class="cell dragEle type0"></div>
          <div class="cell dragEle type1"></div>
          <div class="cell dragEle type4"></div>
          <div class="cell dragEle type3"></div>
          <div class="cell dragEle type1"></div>
        </div>
        <div class="row">
          <div class="cell dragEle type1"></div>
          <div class="cell dragEle type1"></div>
          <div class="cell dragEle type3"></div>
          <div class="cell dragEle type4"></div>
          <div class="cell dragEle type2"></div>
        </div>
        <div class="row">
          <div class="cell dragEle type2"></div>
          <div class="cell dragEle type2"></div>
          <div class="cell dragEle type4"></div>
          <div class="cell dragEle type2"></div>
          <div class="cell dragEle type2"></div>
        </div>
        <div class="row">
          <div class="cell dragEle type0"></div>
          <div class="cell dragEle type1"></div>
          <div class="cell dragEle type4"></div>
          <div class="cell dragEle type3"></div>
          <div class="cell dragEle type1"></div>
        </div>
        <div class="row">
          <div class="cell dragEle type1"></div>
          <div class="cell dragEle type4"></div>
          <div class="cell dragEle type2"></div>
          <div class="cell dragEle type2"></div>
          <div class="cell dragEle type1"></div>
        </div>
      </div> -->
      <div class="createBox">
          by  Melin and IF , July 2017 .
      </div>
    </body>
    <script type="text/javascript">
    var startPositoin ={
        x:0,
        y:0,
        time:0
    };
    var targetRow = 0 , targetCol = 0 ,exRow = 0 ,exCol = 0 ;
    var displacementX = 0 , displacementY = 0 , displacementXABS = 0,displacementYABS = 0;
    var scoreTotle = 0;
    var ROW_MAX = 5;
    var COL_MAX = 5;
    var SPECI_MAX = 5;
    var speciArr = [];
    var initArr1 = [[3,4,2,2,3],
                    [1,4,0,4,2],
                    [1,3,3,1,0],
                    [3,2,4,2,1],
                    [3,4,0,1,3]];
    for (var i = 0; i < SPECI_MAX; i++) {
      speciArr[i] = [[0,0,0,0,0],
                     [0,0,0,0,0],
                     [0,0,0,0,0],
                     [0,0,0,0,0],
                     [0,0,0,0,0]];
    }
    var tipBox = document.getElementById("tipBox");
    var isOpen = false;
    function initDemo(arrParams){
        var tableDemo = document.getElementById("tableBox");
        var cellDemo = '';
        for(var row =0;row<ROW_MAX;row++){
            for(var col =0;col<COL_MAX;col++){
              cellDemo +='<div class="cell dragEle type'+arrParams[row][col]+'" data-index="'+(row*COL_MAX+col)+'"></div>';
            }    
        }
        tableDemo.innerHTML = cellDemo;
    }
    initDemo(initArr1);
    var oriObj = document.getElementById("tableBox");
        oriObj.addEventListener('touchstart', touchS, false );
        oriObj.addEventListener('touchmove',touchM ,  false);
        oriObj.addEventListener('touchend', touchE, false);

    function touchS(ev){
        var ev = ev || window.event;
　　　　var target = ev.target || ev.srcElement;
        var className = target.className;
        if(className.indexOf("dragEle") != -1){
            if(ev.touches.length == 1){
                target.className = className+' '+'active';
                startPositoin.x = ev.touches[0].pageX;
                startPositoin.y = ev.touches[0].pageY;
                startPositoin.time = new Date();
            }
        }
    }

    function touchM(ev){
        var ev = ev || window.event;
　　　　var target = ev.target || ev.srcElement;
        var className = target.className;
        var targetWidth = target.offsetWidth,targetHeight = target.offsetHeight;
        if(className.indexOf("dragEle") != -1){ 
            if(ev.touches.length == 1){
                displacementX = ev.touches[0].pageX - startPositoin.x;
                displacementY = ev.touches[0].pageY - startPositoin.y;
                displacementXABS = Math.abs( displacementX );
                displacementYABS = Math.abs( displacementY );

                if((displacementXABS >= ( targetWidth*0.5 ) && displacementXABS <=( targetWidth*1.5 ) ) || ( displacementYABS >= ( targetHeight*0.5 ) && displacementYABS <= ( targetHeight*1.5 ) )){
                    //console.log("create");
                    //target.style.left = ev.touches[0].pageX + 'px';
                    //target.style.top = ev.touches[0].pageY + 'px';

                }
                if(displacementXABS > ( targetWidth*1.5 )|| displacementYABS > ( targetHeight*1.5 )){
                    //console.log("clear");
                }

            }
        }
        ev.preventDefault();
    }
    function touchE(ev){
        var ev = ev || window.event;
　　　　var target = ev.target || ev.srcElement;
        var className = target.className.replace('active','');
        target.className = className;
        var targetWidth = target.offsetWidth,targetHeight = target.offsetHeight;
        var parentEle = null , exEle = null , exEleClass = '';
        var targetIndex = 0 , exIndex = -1;
        var upFlag = true , downFlag = true , leftFlag = true , rightFlag = true ;
        if(className.indexOf("dragEle") != -1){
            if(ev.changedTouches.length == 1){
                displacementX = ev.changedTouches[0].pageX - startPositoin.x;
                displacementY = ev.changedTouches[0].pageY - startPositoin.y;
                displacementXABS = Math.abs( displacementX );
                displacementYABS = Math.abs( displacementY );
                parentEle = target.parentElement;
                for(var i = 0 ; i<parentEle.childNodes.length ; i++){
                    if( parentEle.childNodes[i].nodeType == 1){
                        if(parentEle.childNodes[i].dataset.index == target.dataset.index){
                            targetIndex = target.dataset.index;
                            if(targetIndex < COL_MAX){
                                //第一行
                                upFlag = false;
                            }
                            if( (targetIndex%COL_MAX) == 0){
                                //最左列
                                leftFlag = false;
                            }
                            if( (targetIndex%COL_MAX) == (COL_MAX-1) ){
                                //最右列
                                rightFlag = false;
                            }
                            if((targetIndex >= COL_MAX*(ROW_MAX-1)) && (targetIndex < COL_MAX*ROW_MAX)){
                                //最后一行
                                downFlag = false;
                            }
                        }
                    }
                }

                if((displacementXABS >= ( targetWidth*0.5 ) && displacementXABS <=( targetWidth*1.5 ) ) || ( displacementYABS >= ( targetHeight*0.5 ) && displacementYABS <= ( targetHeight*1.5 ) )){  
                    //向上
                    if((displacementY<0&&displacementX>0&&displacementYABS>displacementXABS)||(displacementY<0&&displacementX<0&&displacementYABS>displacementXABS)){
                        if(upFlag){
                           console.log("向上");
                           exIndex =  parseInt(targetIndex, 10) - COL_MAX;
                        } 
                    }
                    //向下
                    if((displacementY>0&&displacementX<0&&displacementYABS>displacementXABS)||(displacementY>0&&displacementX>0&&displacementYABS>displacementXABS)){
                        if(downFlag){
                           console.log("向下"); 
                           exIndex =  parseInt(targetIndex, 10) + COL_MAX;
                        }
                    }
                    //向右
                    if((displacementY<0&&displacementX>0&&displacementYABS<displacementXABS)||(displacementY>0&&displacementX>0&&displacementYABS<displacementXABS)){
                        if(rightFlag){
                           console.log("向右"); 
                           exIndex =  parseInt(targetIndex, 10) + 1;
                        }
                    }
                    //向左
                    if((displacementY<0&&displacementX<0&&displacementYABS<displacementXABS)||(displacementY>0&&displacementX<0&&displacementYABS<displacementXABS)){
                        if(leftFlag){
                           console.log("向左"); 
                           exIndex =  parseInt(targetIndex, 10) - 1;
                        }
                    }  
                }
                
                if(exIndex >= 0){
                    //交换
                    targetRow = Math.floor(targetIndex/COL_MAX);
                    targetCol = targetIndex%COL_MAX;
                    exRow = Math.floor(exIndex/COL_MAX);
                    exCol = exIndex%COL_MAX;

                    // for(var m = 0 ; m <parentEle.childNodes.length ; m++){
                    //     if(parentEle.childNodes[m].dataset.index == targetIndex){
                    //         exEleClass = parentEle.childNodes[m].className;
                    //         exEle = parentEle.childNodes[m].innerHTML;
                    //         break;
                    //     }  
                    // }
                    // for(var n = 0 ; n <parentEle.childNodes.length ; n++){
                    //     if(parentEle.childNodes[n].dataset.index == exIndex){
                    //         target.className = parentEle.childNodes[n].className;
                    //         target.innerHTML = parentEle.childNodes[n].innerHTML;
                    //         parentEle.childNodes[n].className = exEleClass;
                    //         parentEle.childNodes[n].innerHTML = exEle;
                    //         break;
                    //     }  
                    // }
                    console.log("targetRow: "+targetRow);
                    console.log("targetCol: "+targetCol);
                    console.log("exRow: "+exRow);
                    console.log("exCol: "+exCol);
                    mainProcess(targetRow,targetCol,exRow,exCol); 

                }

            }
        }
    }

    function handleArr(arrParams){
        var res = 0;
        for (var row = 0; row < ROW_MAX; row++) {
            for (var col = 0; col < COL_MAX - 2; col++) {
                if (arrParams[row][col] == arrParams[row][col + 1]) {
                    if (arrParams[row][col] == arrParams[row][col + 2]) {
                        res = 1;
                        speciArr[arrParams[row][col]][row][col]++;
                        speciArr[arrParams[row][col]][row][col + 1]++;
                        speciArr[arrParams[row][col]][row][col + 2]++;
                        if (col + 3 >= COL_MAX) {
                            col += 3;
                            continue;
                        }
                        if (arrParams[row][col] == arrParams[row][col + 3]) {
                            speciArr[arrParams[row][col]][row][col + 3]++;
                            if (col + 4 >= COL_MAX) {
                                col += 4;
                                continue;
                            }
                            if (arrParams[row][col] == arrParams[row][col + 4]) {
                                speciArr[arrParams[row][col]][row][col + 4]++;
                                col += 5;
                            }
                        }
                    }
                }
            }
        }
        for (var col = 0; col < COL_MAX; col++) {
            for (var row = 0; row < ROW_MAX - 2; row++) {
                if (arrParams[row][col] == arrParams[row + 1][col]) {
                    if (arrParams[row][col] == arrParams[row + 2][col]) {
                        res = 1;
                        speciArr[arrParams[row][col]][row][col]++;
                        speciArr[arrParams[row][col]][row + 1][col]++;
                        speciArr[arrParams[row][col]][row + 2][col]++;
                        if (row + 3 >= ROW_MAX) {
                            row += 3;
                            continue;
                        }
                        if (arrParams[row][col] == arrParams[row + 3][col]) {
                            speciArr[arrParams[row][col]][ row + 3][col]++;
                            if (row + 4 >= ROW_MAX) {
                                row += 4;
                                continue;
                            }
                            if (arrParams[row][col] == arrParams[row + 4][col]) {
                                speciArr[arrParams[row][col]][row+ 4][col]++;
                                row += 5;
                            }
                        }
                    }
                }
            }
        }

        return res;
    }
    function printArr(arr) {
      console.log("-------------");
      for (var row = 0; row < ROW_MAX; row++) {
        console.log(row + ":" + JSON.stringify(arr[row]));
      }
      console.log("-------------");
    }

    
    function calcScore(speciArr){
        var score = 0;
        for (var row = 0; row < ROW_MAX; row++) {
            for (var col = 0; col < COL_MAX; col++) {
              if(speciArr[row][col]>0){
                score += speciArr[row][col];  
              }        
            }
        }
        switch(score){
          case 3:
            score = score*1;
            break;
          case 4:
            score = score*1;
            break;
          case 5:
            score = score*2;
            break;
          case 6:
            score = score*3;
            break;
          case 7:
            score = score*3+1;
            break;
          case 8:
            score = score*3+2;
            break;

        }
        scoreTotle +=score;
    }
    function refreshArr(arr, rspeci){
        // 遍历每一列
        for (var col = 0; col < COL_MAX; col++){
          var cntNoneZero = 0;
          var firstNoneZeroRow;
          for (var row = ROW_MAX - 1; row >= 0; row--) {
            if (cntNoneZero == 0) {
              // 从下往上找第一个非0
              if (rspeci[row][col] > 0) {
                cntNoneZero++;
                firstNoneZeroRow = row;
              }
            } else {
              // 找到第一个非0后，计非0的个数
              if (rspeci[row][col] > 0) {
                cntNoneZero++;
              } else {
                break;
              }
            }
          }
          if (cntNoneZero > 0) {
            for (var i = firstNoneZeroRow; i >= 0 ; i--) {
              if (i - cntNoneZero >= 0) {
                clearAnimate(i,col,cntNoneZero,initArr1);
                initArr1[i][col] = initArr1[i - cntNoneZero][col];
                
              } else {
                clearAnimate(i,col,cntNoneZero,initArr1);
                //Math.floor(Math.random()*(max-min+1)+min);
                initArr1[i][col] = Math.floor(Math.random() * SPECI_MAX);
                
              }
            }
          }
        }
    }
    // requestAnimationFrame的兼容处理
    if (!window.requestAnimationFrame) {
        requestAnimationFrame = function(fn) {
            setTimeout(fn, 17);
        };  
    }
    function clearAnimate(row,col,cnt,arr){
        var tableBox = document.getElementById("tableBox");
        var newDemo = document.createElement("div");
        var startX = 0,startY = 0,endX = 0,endY = 0;
        var targetIndex = (row*COL_MAX)+col;
        var targetEle = null;
        for(var i = 0 ; i<tableBox.childNodes.length ; i++){
            if( tableBox.childNodes[i].nodeType == 1){
                if(tableBox.childNodes[i].dataset.index == targetIndex){
                    targetEle = tableBox.childNodes[i]
                }
            }
        }

        endX= targetEle.getBoundingClientRect().left+document.documentElement.scrollLeft; 
        endY =targetEle.getBoundingClientRect().top+document.documentElement.scrollTop;
        if(row-cnt >= 0){
          newDemo.className = 'cell animateEle'+' '+'type'+arr[row-cnt][col];
          startY = endY-50;
           
        }else{
            newDemo.className = 'cell animateEle'+' '+'type'+Math.floor(Math.random() * SPECI_MAX);
            startY = endY-70;
        }
        startX = endX;
        
        newDemo.style.top = startY + 'px';
        newDemo.style.left = endX + 'px';
        document.body.appendChild(newDemo);
        //A = A + (B - A) / 2

         var down = function () {
        startY = startY + (endY - startY) / 5;
        console.log(startY);
        
        // 临界判断，终止动画
        if (startY > (endY-5)) {
            console.log('here');
            newDemo.parentNode.removeChild(newDemo);
            return;
        }
        newDemo.style.top = startY + 'px';
        // 动画gogogo!
        requestAnimationFrame(down);    
    };
    down();

    }

    function clearArr(arr) {
      for (var row = 0; row < ROW_MAX; row++) {
        for (var col = 0; col < COL_MAX; col++) {
          arr[row][col] = 0;
        }
      }
    }

    function switchArr(initArr1, row1, col1, row2, col2) {
        var a = initArr1[row1][col1];
        initArr1[row1][col1] = initArr1[row2][col2];
        initArr1[row2][col2] = a; 
    }

    function mainProcess(targetRow,targetCol,exRow,exCol) {
        var res = 0;
        switchArr(initArr1, targetRow, targetCol, exRow, exCol);
        initDemo(initArr1);
        res = handleArr(initArr1);
        console.log("res : "+res)
        if (res == 0) {
            switchArr(initArr1, targetRow, targetCol, exRow, exCol);
            initDemo(initArr1);
            return;
        }

        while (res == 1) {

            for (var i = 0; i < SPECI_MAX; i++) {
                calcScore(speciArr[i]);
            }
            for (var i = 0; i < SPECI_MAX; i++) {
                refreshArr(initArr1, speciArr[i]);
            }
            for (var i = 0; i < SPECI_MAX; i++) {
                clearArr(speciArr[i]);
            }

            res = handleArr(initArr1);

        }
        printArr(initArr1);
        initDemo(initArr1);
        document.getElementById("scoreBox").innerHTML  = scoreTotle;
        if(scoreTotle>10){
            if(isOpen){
                return false;
            }
            tipBox.style.display = 'block';
            isOpen = true;
            setTimeout(function(){
              tipBox.style.display = 'none';  
            },1500)

            
        }
    }
  
    </script>
    </html> 